from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
import time

from common.log import log

class AccessMiddleware(BaseHTTPMiddleware):
    """
    记录请求日志
    """
    
    async def dispatch(self, request: Request, call_next) -> Response:
        if "x-forwarded-for" in request.headers:
            client_host = request.headers["x-forwarded-for"].split(",")[0]
        else:
            client_host = request.client.host if request.client else "unknown"
        start_time = time.perf_counter() * 1000
        response = await call_next(request)
        end_time = time.perf_counter() * 1000
        interval = end_time - start_time
        time_info = f"{round(interval / 1000, 2)} s" if interval > 1000 else f"{int(interval)} ms"
        log.info(f'{response.status_code} {client_host} {request.method} {request.url} {time_info}')
        return response